<?php

namespace app\controller;


use think\helper\Str;

class Auth extends Base
{

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 权限鉴定中心
     * api post /auth/appraisal
     */
    public function appraisal()
    {
        Token::apisecurity(false);
        _Success('鉴权成功');
    }

    /**
     * 应用accesstoken
     * api post /auth/accessToken
     * @param string appId
     * @param string appSecret
     * @return json accessToken 应用凭证
     */
    public function accessToken()
    {
        if (_isget()) {
            $appId = isset(_get()['appId']) ? _get()['appId'] : '';
            $appSecret = isset(_get()['appSecret']) ? _get()['appSecret'] : '';

            if (!$appId && !$appSecret) {
                _Error('请求失败，应用凭证未提交');
            }
            $appSelect = db('app', 'mysql')->where('app_id', $appId)->field('id,app_id,app_secret')->where('app_secret', $appSecret)->cache('getAppFind_' . $appId)->find();
            if (!$appSelect) {
                _Error('请求失败，错误的应用凭证');
            }
            $return = Token::createSecret($appSelect);
            $this->redis->select(2);
            if (!$this->redis->get($appSelect['app_id'])) {
                $this->redis->set($appSelect['app_id'], $return);
            }

            // $this->redis->expire($appSelect['app_id'],2592000);

            _Success('应用凭证', 200, $return);
        }
        _Result('响应失败', 500);
    }


    /**
     * 登录
     * api post /auth/login
     * @param string account 登录用户
     * @param string password 登录密码
     * @param string code 微信登录使用
     * @return json token 用户凭证
     * @return json secret 门店凭证
     */
    public function login()
    {
        if (_ispost()) {
            // Token::apisecurity(false);
            if (isset(_post()['account']) && _post()['account'] && isset(_post()['password']) && _post()['password']) {
                $userinfo = db('users', 'mysql')->field('login_nums,id,openid,unionid,nickname')->where('account', _post()['account'])->where('truepass', _post()['password'])->find();
                $openid = $userinfo['openid'];
            } else {
                $openid = "oIgYg1FI6WBi6rxl7IyiqLFHwW84";
                $userinfo = db('users', 'mysql')->field('login_nums,id,openid,unionid,nickname')->where('openid', $openid)->find();
            }
            if (!$userinfo) {
                _Error('用户信息错误');
            }
            
            // $secret = [
            //     'openid' => $openid,
            //     'unionid' => $userinfo['unionid'],
            //     'id' => $userinfo['id'],
            // ];

            if (isset(_post()['session']) && _post()['session'] == 'true') {
                session("userinfo", $userinfo);
            }

            //创建用户token
            $return = [
                'token' => Token::createToken($userinfo['id']),
                // 'secret' => Token::createSecret($secret),
            ];


            //设置redis
            $this->redis->select(1);
            $redisdata = $this->redis->get('users-token-' . $userinfo['id']);
            if ($redisdata) {
                $redisdataarray = @explode('|', $redisdata);
                foreach ($redisdataarray ? $redisdataarray : [] as $key => $value) {
                    $exp = str2arr($value);
                    if (!$exp[1]) {
                        unset($redisdataarray[$key]);
                    } else {
                        if ($exp[1] <= time()) {
                            unset($redisdataarray[$key]);
                        }
                    }
                }
                if (@count($redisdataarray) >= 10) {
                    array_shift($redisdataarray);
                };
                if (!$redisdataarray) {
                    setReids(1, 'users-token-' . $userinfo['id'], $return['token'] . ',' . (time() + 259200));
                } else {
                    array_push($redisdataarray, ($return['token'] . ',' . (time() + 259200)));
                    setReids(1, 'users-token-' . $userinfo['id'], arr2str($redisdataarray, '|'));
                }
            } else {
                setReids(1, 'users-token-' . $userinfo['id'], $return['token'] . ',' . (time() + 259200));
            }
            //设置reids

            $logininfo = [
                'login_nums' => $userinfo['login_nums']+1,
                'login_time' => time(),
            ];
            db('users', 'mysql')->where('id', $userinfo['id'])->update($logininfo);
            // Token::setCache($userinfo['id'], $return['token'],$return['secret']);
            _Success('登录成功', 200, $return);
        }
        _Result('响应失败', 500);
    }
}
